﻿/*
 * by cansik / Florian
 * Datum: 29.04.2009
 * Zeit: 10:55
 */
using System;
using System.Text;
using CML;
using System.Windows.Forms;
using System.IO;
using ProviderHandler;
using System.Security.Cryptography;

namespace sEmit.Core
{
    public class sEmitCommandLine
    {
        const string logfile = ("sms.log");

        IWebSMSHandler wsmsh;

        String Provider {get; set; }

        String Number {get; set;}
        String Password { get; set; }

        String Receiver {get; set;}
        String Message {get; set;}

        public sEmitCommandLine()
        {
        }

        public Boolean Prepair(String[] arguments)
        {
            if (ReadConfig(arguments[0]) == true)
            {
                Receiver = arguments[1];
                Message = arguments[2];

                if (LoadProvider("providers", "IWebSMSHandler") == true)
                {
                    wsmsh.LoginName = Number;
                    wsmsh.Password = Password;
                    return true;
                }
                else
                {
                    Console.Error.WriteLine("coud not load the provider!");
                    return false;
                }
            }
            else
            {
                Console.Error.WriteLine("coud not read the config!");
                return false;
            }
        }
        public Boolean SendSMS()
        {
            try
            {
                if (wsmsh.Login() == true)
                {
                    wsmsh.SendSMS(Receiver, Message);
                    WriteLog(new Contact(SystemInformation.ComputerName, Number), new Contact(Receiver, Receiver), Message);
                    return true;
                }
                else
                {
                    Console.Error.WriteLine("coud not login!");
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                return false;
            }
        }

        private Boolean ReadConfig(String configfile)
        {
            if (File.Exists(configfile))
            {
                CMLReader reader = new CMLReader(configfile);
                reader.ReadFile(false);

                Number = reader.GetElement("data").Attributes["number"];
                Password = reader.GetElement("data").Attributes["password"];
                Provider = reader.GetElement("data").Attributes["provider"];

                reader.Close();
                return true;
            }
            else
            {
                return false;
            }
        }
        private Boolean LoadProvider(string directory, string strInterface)
        {
            PluginServices.AvailablePlugin[] providers = PluginServices.FindPlugins(directory, strInterface);
            if (providers != null)
            {
                foreach (PluginServices.AvailablePlugin provider in providers)
                {
                   IWebSMSHandler wsmshProvider = (IWebSMSHandler)PluginServices.CreateInstance(provider);
                   if (wsmshProvider.Name.ToLower() == Provider.ToLower())
                   {
                       wsmsh = wsmshProvider;
                       wsmsh.Initialize();
                       return true;
                   }
                }
            }
            return false;
        }
        private void WriteLog(Contact From, Contact To, string message)
        {
            string log = "<!$" + GetMD5Hash(DateTime.Now.ToString() + DateTime.Now.Ticks.ToString()) + " datum='" + DateTime.Now.ToString() + "' fromName='" + From.Name + "' fromNR='" + From.Number + "' toName='" + To.Name + "' toNR='" + To.Number + "' message='" + message.Replace("\r", "\\r").Replace("\n", "\\n") + "' />\n";
            File.AppendAllText(logfile, log);
        }
        private string GetMD5Hash(string TextToHash)
        {
            //Prüfen ob Daten übergeben wurden.
            if ((TextToHash == null) || (TextToHash.Length == 0))
            {
                return string.Empty;
            }

            //MD5 Hash aus dem String berechnen. Dazu muss der string in ein Byte[]
            //zerlegt werden. Danach muss das Resultat wieder zurück in ein string.
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] textToHash = Encoding.Default.GetBytes(TextToHash);
            byte[] result = md5.ComputeHash(textToHash);

            return System.BitConverter.ToString(result);
        }
    }
}
